/**
 * Author: Jordi Vilaplana Mayoral <jvilaplana@alumnes.udl.cat>
 * Date: 05/04/2011
 * 
 * LocationManager
 * Copyright (C) 2011 Jordi Vilaplana Mayoral
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * @(#)
 * Description: This program allows users to book rooms and schedule activities
 */

package locmanager.servlets;

import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import locmanager.beans.ActivityBean;
import locmanager.beans.LocationBean;
import locmanager.persistence.DerbyPersistence;

/**
 * Location Filter Controller.
 * 
 * @author Jordi Vilaplana Mayoral <jvilaplana@alumnes.udl.cat>
 * @version 1.0
 */
public class LocationFilterServlet extends HttpServlet {

  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {

    response.setContentType("X-JSON");
    PrintWriter out = response.getWriter();

    int maxStudents = -1;
    int duration = -1;
    int roomTypeId = -1;
    Date startDate = null;
    SimpleDateFormat formater = null;
    String[] locationEquipments;
    List<ActivityBean> activities = null;

    DerbyPersistence db = new DerbyPersistence();
    List<LocationBean> locations = db.getLocations();
    List<LocationBean> filteredLocations = new ArrayList<LocationBean>();

    if (isNumber(request.getParameter("maxStudents"))) {
      System.out.println("Filtering maxStudents...");
      maxStudents = Integer.parseInt((String) request.getParameter("maxStudents"));

      for (LocationBean location : locations) {
        if (location.getCapacity() >= maxStudents) {
          filteredLocations.add(location);
        }
      }
      locations.clear();
      locations.addAll(filteredLocations);
      filteredLocations.clear();
    }

    if (isNumber(request.getParameter("roomTypeId"))) {

      roomTypeId = Integer.parseInt((String) request.getParameter("roomTypeId"));
      System.out.println("Filtering roomTypeId(" + roomTypeId + ")...");

      for (LocationBean location : locations) {
        System.out.println("locrti = " + location.getRoomTypeId());
        if (location.getRoomTypeId() == roomTypeId) {
          filteredLocations.add(location);
        }
      }
      locations.clear();
      locations.addAll(filteredLocations);
      filteredLocations.clear();

    }

    if (request.getParameterValues("locationEquipments") != null) {

      locationEquipments = request.getParameterValues("locationEquipments");

      for (LocationBean location : locations) {
        boolean allEquipments = true;
        for (String equipment : locationEquipments) {
          if (!location.hasEquipment(Integer.parseInt(equipment))) {
            allEquipments = false;
          }
        }
        if (allEquipments) {
          filteredLocations.add(location);
        }
        locations.clear();
        locations.addAll(filteredLocations);
        filteredLocations.clear();
      }

    }

    if (isNumber(request.getParameter("duration"))) {
      duration = Integer.parseInt((String) request.getParameter("duration"));
    }
/*
    if (duration != -1 && request.getParameter("startDate") != null) {

      formater = new SimpleDateFormat("yyyy-MM-dd");

      try {
        startDate = formater.parse((String) request.getParameter("startDate"));
      } catch (ParseException ex) {
      }

      if (startDate != null) {

        for (LocationBean location : locations) {

          activities = db.getActivitiesByLocation(location, startDate);

          int totalDuration = duration;
          for (ActivityBean activity : activities) {
            totalDuration += activity.getDuration();
          }
          filteredLocations.add(location);
        }
        locations.clear();
        locations.addAll(filteredLocations);
        filteredLocations.clear();

      }

    }
*/
    Gson gson = new Gson();
    String jsonOutput = gson.toJson(locations);

    try {
      out.write(jsonOutput);

    } finally {
      out.close();
    }


  }

  private boolean isNumber(String parameter) {

    if (parameter != null) {
      try {
        Integer.parseInt((String) parameter);
        return true;
      } catch (NumberFormatException e) {
        return false;
      }

    }

    return false;

  }

  /**
   * Handles the HTTP <code>GET</code> method.
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    processRequest(request, response);
  }

  /**
   * Handles the HTTP <code>POST</code> method.
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
    processRequest(request, response);
  }

}
